// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db=cloud.database()
const _=db.command
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID;
  const { gift, fuserInfo, senderUserInfo}=event;
  let fop=fuserInfo.openId;
  let gidstr=gift._id;

  try{
    //判断用户金币是否足够
   let procoin= await db.collection('userGold').where({
      openid
    }).get();
    if(procoin.data[0].goldNum<gift.price){
      return{
        code:2,
        mes:'金币不够'
      }
    }
    //判断被赠送的用户是否在榜上
    let proc=await db.collection('giftPhb').where({
      openid:fop
    }).count();
    let time=new Date().getTime();
    if(proc.total==0){
      await db.collection('giftPhb').add({
        data:{
          openid:fop,
          userData:fuserInfo,
          newReceive: [{ giftName: gift.name, num: 1, senderUserInfo,time}],
          allReceive: { [gift._id]:1},
          meiLi: gift.experience,
          dayRec:gift.experience,
          weekRec:gift.experience,
          monthRec:gift.experience,
          dup:[],
          wup:[],
          mup:[]
        }
      });
    }
    else {
      await db.collection('giftPhb').where({
        openid:fop
      }).update({
        data:{
          userData:fuserInfo,
          newReceive: _.unshift({ giftName: gift.name, num: 1, senderUserInfo,time}),
          ['allReceive.'+gidstr+'']:_.inc(1),
          meiLi: _.inc(gift.experience),
          dayRec: _.inc(gift.experience),
          weekRec:_.inc(gift.experience),
          monthRec: _.inc(gift.experience)
        }
      })
    }

    //给gift表对应的礼物上面总的赠送量+1
    await db.collection('gift').where({
      _id: gidstr
    }).update({
      data:{
        giveNum:_.inc(1),
        saleNum:_.inc(1)
      }
    });

    //扣除赠送者的金币
    await db.collection('userGold').where({
      openid
    }).update({
      data:{
        goldNum:_.inc(-gift.price)
      }
    });

    return{
      code:0,
      mes:'赠送成功'
    }
  }catch(e){
    return{
      code: 1,
      mes: '赠送失败'
    }
  }
}